"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 服务端工具
Case Name   : 有admin权限用户执行flush binary logs
Create At   : 2022/10/19
@zou_jialiang0501129488
Description :
    1.创建兼容B数据库
    2.设置guc参数archive_mode=on并重启数据库
    3.执行建表操作
    4.执行flush binary logs操作
    5.查看归档目录文件状态
    6.清理环境
Expect      :
    1.创建成功
    2.guc参数设置成功
    3.成功
    4.成功
    5.文件生成正确
    6.成功
History     :
    modified by @zou_jialiang050 at 2023-6-8:修改数据库重启使用公共方法，防止Degraded状态断言失败
"""
import os
import re
import time
import unittest

from yat.test import Node
from yat.test import macro

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger

Constant = Constant()


class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.common = Common()
        self.primary_root_node = Node('PrimaryRoot')
        self.primary_node = Node('PrimaryDbUser')
        self.comsh_p = CommonSH("PrimaryDbUser")
        self.archive_path = os.path.join(macro.PG_XLOG_PATH, 'archive_status')

    def test_flush(self):
        text = '-----step1:创建兼容B库 expect:成功-----'
        self.log.info(text)
        sql_cmd = f"drop database if exists db_flush_case0001;" \
                  f"create database db_flush_case0001 " \
                  f"dbcompatibility ='B' encoding ='UTF8';"
        self.log.info(sql_cmd)
        sql_res = self.comsh_p.execut_db_sql(sql_cmd, dbname='postgres')
        self.log.info(sql_res)
        self.assertIn(Constant.CREATE_DATABASE_SUCCESS, sql_res,
                      '执行失败' + text)

        text = '-----step2:设置guc参数archive_mode=on并重启数据库 expect:成功-----'
        self.log.info(text)
        res = self.comsh_p.execute_gsguc('set', Constant.GSGUC_SUCCESS_MSG,
                                         param='archive_mode=on',
                                         get_detail=True)
        self.assertIn(Constant.GSGUC_SUCCESS_MSG, res, 'guc设置失败')
        restart = self.comsh_p.restart_db_cluster(get_detail=True)
        self.assertIn(Constant.GS_OM_START_SUCCESS_MSG, restart, '数据库重启失败')

        text = '-----step3:执行建表操作 expect:成功-----'
        self.log.info(text)
        sql = 'drop table if exists t_flush_case0001;' \
              'create table t_flush_case0001(c1 int);'
        res = self.comsh_p.execut_db_sql(sql, dbname='db_flush_case0001')
        self.log.info(res)
        self.assertIn(Constant.CREATE_TABLE_SUCCESS, res, '建表失败')

        text = '-----step4:执行flush binary logs操作 expect:成功-----'
        self.log.info(text)
        sql = "flush binary logs;"
        flush_res = self.comsh_p.execut_db_sql(sql, dbname='db_flush_case0001')
        self.log.info(flush_res)
        self.assertIn('(1 row)', flush_res, 'flush失败')
        physical_id = re.findall('[0-9A-Z]{2}', flush_res.splitlines()[-2].
                                 strip().split('/')[-1].rjust(8, '0'))[0]
        self.log.info(physical_id)
        time.sleep(10)

        text = '-----step5:查看归档文件状态 expect:成功-----'
        self.log.info(text)
        cmd = f'ls {self.archive_path}'
        self.log.info(cmd)
        res = self.common.get_sh_result(self.primary_node, cmd)
        self.assertTrue(res, '查看失败')
        status_id = re.findall('[0-9A-Z]{8}', res)[-1]
        self.log.info(status_id)
        self.assertEqual(int(physical_id, 16), int(status_id, 16), 'flush操作失败')

    def tearDown(self):
        text = "-----step6:清理环境 expect:成功-----"
        self.log.info(text)
        sql_cmd = f"drop database if exists db_flush_case0001;"
        self.log.info(sql_cmd)
        sql_res = self.comsh_p.execut_db_sql(sql_cmd, dbname='postgres')
        self.log.info(sql_res)
        res = self.comsh_p.execute_gsguc('set', Constant.GSGUC_SUCCESS_MSG,
                                         param='archive_mode=off',
                                         get_detail=True)
        self.comsh_p.restart_db_cluster()
        status = self.comsh_p.get_db_cluster_status(param='status')
        self.assertIn(Constant.DROP_DATABASE_SUCCESS, sql_res, '执行失败' + text)
        self.assertIn(Constant.GSGUC_SUCCESS_MSG, res, 'guc设置失败')
        self.assertTrue(status, '数据库状态异常')
        self.log.info(f'-----{os.path.basename(__file__)} finish-----')
